Why do I get this exception? {An item with the same key has already been added."})

Posted by Alan on Stack Overflow See other posts from Stack Overflow or by Alan
Published on 2009-08-20T00:32:46Z Indexed on 2011/11/12 9:51 UTC
Read the original article Hit count: 197

Filed under:

Aknittel
NewSellerID is the result of a lookup on tblSellers. These tables (tblSellerListings and tblSellers) are not "officially" joined with a foreign key relationship, either in the model or in the database, but I want some referential integrity maintained for the future. So my issue remains. Why do I get the exception ({"An item with the same key has already been added."}) with this code, if I don't begin each iteration of the foreach loop with a new ObjectContext and end it with SaveChanges, which I think will affect performance. Also, could you tell me why ORCSolutionsDataService.tblSellerListings (An ADO.NET DataServices/WCF object is not IDisposable, like LINQ to Entities??

==============================================

// Add listings to previous seller
int NewSellerID = 0;

// Look up existing Seller key using SellerUniqueEBAYID
var qryCurrentSeller = from s in service.tblSellers
					   where s.SellerEBAYUserID == SellerUserID
					   select s;

foreach (var s in qryCurrentSeller)
	NewSellerID = s.SellerID;

// Save the selected listings for this seller

foreach (DataGridViewRow dgr in dgvRows)
{

	ORCSolutionsDataService.tblSellerListings NewSellerListing = new ORCSolutionsDataService.tblSellerListings();
	NewSellerListing.ItemID = dgr.Cells["txtSellerItemID"].Value.ToString();
	NewSellerListing.Title = dgr.Cells["txtSellerItemTitle"].Value.ToString();
	NewSellerListing.CurrentPrice = Convert.ToDecimal(dgr.Cells["txtSellerItemPrice"].Value);
	NewSellerListing.QuantitySold = Convert.ToInt32(dgr.Cells["txtSellerItemSold"].Value);
	NewSellerListing.EndTime = Convert.ToDateTime(dgr.Cells["txtSellerItemEnds"].Value);
	NewSellerListing.CategoryName = dgr.Cells["txtSellerItemCategory"].Value.ToString();
	NewSellerListing.ExtendedPrice = Convert.ToDecimal(dgr.Cells["txtExtendedReceipts"].Value);
	NewSellerListing.RetrievedDtime = Convert.ToDateTime(dtSellerDataRetrieved.ToString());
	NewSellerListing.SellerID = NewSellerID;

	service.AddTotblSellerListings(NewSellerListing);

}

service.SaveChanges();

}

catch (Exception ex) { MessageBox.Show("Unable to add a new case. Exception: " + ex.Message);

}

© Stack Overflow or respective owner

Related posts about linq-to-entities